﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;
using WebSOAPUI.Lib;

namespace System.Web.UI
{
    public static class PageExtensions
    {
        public static void HandleAJAXRequest(this Page page)
        {
            var isAjax = page.Request.QueryString["ajax"].ToBoolean();
            if (isAjax)
            {
                page.Response.ContentType = "application/json";
                var methodName = page.Request.QueryString["m"];
                if (string.IsNullOrEmpty(methodName))
                    return;
                var methodInfo = page.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.IgnoreCase
                    | BindingFlags.NonPublic);
                if (methodInfo != null)
                {
                    methodInfo.Invoke(page, null);
                    page.Response.End();
                }
            }
        }

       

        public static void ResponseJSON(this Page page, object @object, string datetimeFormat = "")
        {
            var json = JsonConvert.SerializeObject(@object, Formatting.None,
                new DefaultDateTimeConverter(datetimeFormat));
            page.Response.Write(json);

        }

        public static T DeserializeObject<T>(this Page page, String json, string datetimeFormat = "")
        {
            return JsonConvert.DeserializeObject<T>(json, new DefaultDateTimeConverter(datetimeFormat));
        }

        public static void ShowErrorMessage(this Page page, String key, String message)
        {

            var errorJs = "alert('" + page.Server.HtmlEncode(message.Replace("\r", "\\r").Replace("\n", "\\n")) + "');";
            //page.RegisterClientScriptBlock(key, errorJs);
            //page.ClientScript.RegisterClientScriptBlock(page.GetType(), key, errorJs, true);

            ScriptManager.RegisterClientScriptBlock(page, page.GetType(),
                key, errorJs, true);
        }
    }
}